<?php
function game_go(&$arrReturn)
{
    global $db;
    $speNo = $_GET['no'];
    
    if(date( "H" ) < 9)
    {
    	//取下期时间
    	$sql = "SELECT id,kgtime FROM game28 WHERE kj = 0 AND kgtime > NOW() order by id limit 1";
        $query = $db->query($sql);
        if($rs = $db->fetch_array( $query ))
        {
             $arrRet['nextid'] = $rs['id'];
             $arrRet['nexttime'] = $rs['kgtime'];
        }
        else
        {
			 $sql = "select DATE_ADD(NOW(),INTERVAL 60 SECOND) nowtime";
        	 $query = $db->query($sql);
        	 $rs = $db->fetch_array( $query );
			 $arrRet['nextid'] ='0';
             $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime($rs["nowtime"]));
        }
    	$arrReturn['msg'] = 'not in open game time(bj)';
    	return;
	}
    
    $No = intval($speNo);
    $arrCatchNo = array();
    if($speNo == 0) //取最新开奖
    {
		$sql = "SELECT id FROM game28 WHERE kj = 0 AND kgtime < NOW() AND kgtime > DATE_ADD(NOW(),INTERVAL -10 MINUTE)
		        and id not in(select gameno from game_result where gametype = 'gamebj')
			ORDER BY id DESC";
				//die($sql);


    	$query = $db->query($sql);
    	$i = 0;
    	while($rs = $db->fetch_array( $query ))
    	{

				$arrCatchNo[$i] = $rs["id"];
				$i++;

		} 
    }
    else
    {
		$sql = "SELECT id FROM game28 WHERE kj = 0 and id = '{$No}' ";
    	$query = $db->query($sql);
    	if($rs = $db->fetch_array( $query ))
    	{
			$num=Get360Json($rs['id']);
			if($num!=''){
				$sql = "call web_savecatch_result('gamebj',{$rs['id']},'{$num}')";
				$arrT = $db->Mysqli_Multi_Query($sql);
			}else {
				$arrCatchNo[0] = $rs["id"];
			}
		}
    	else
    	{ 
    		$arrReturn['code'] = "ok";
    		$arrReturn['msg'] = "{$No} had opened(bj)";
    		$arrReturn['log'] .= LogFormat("{$No} had opened(bj)");
    		return;
		}
    }
    if(count($arrCatchNo) == 0)
    {
    	 CatchResult($arrCatchNo);
		 $arrReturn['code'] = "ok";
		 $arrReturn['no'] = "0";
    	 $arrReturn['msg'] = "no record to catch(bj)";
    	 $arrReturn['log'] .= LogFormat("no record to catch(bj)");
    	 return;
    }
    
    $ret = CatchResult($arrCatchNo);
    if ( $ret != "")
    {
		$arrReturn['code'] = "ok";
		$arrRet['nextid'] = "catch_ok";
		$arrReturn['msg'] = "catch_ok";
		$arrReturn['no'] = $ret; 
		$strlog = "catched bj: {$ret},result had been saved(bj)";
    	$arrReturn['log'] .= LogFormat($strlog);
    }
    else //取不到结果
	{
		$ret = implode(',',$arrCatchNo);
		$arrReturn['code'] = 'ok';
		$arrReturn['no'] = $ret; 
		$arrReturn['msg'] = "can not catch {$ret} result(hg)";
		$arrReturn['log'] = LogFormat("can not catch {$ret} result!(bj)");
	} 
}

function CatchResult($arr)
{
	global $db;
	$ret = "";
	$kjcontent = GetGameResult();
	if(is_array($kjcontent) || strlen($kjcontent) > 0)
	{   
		//die('111');
		foreach($arr as $key => $v)
		{
			$rewardstr = "";
			//die('2221');
			if(is_array($kjcontent))
			{
				$numberstr = "";
				for($i = 0; $i < count($kjcontent); $i++)
				{
					if($kjcontent[$i]["c_t"] == $v)
					{
						$arrTmp = explode(",",$kjcontent[$i]["c_r"]);
						array_pop($arrTmp);//去掉最后一个
						$numberstr = implode("|",$arrTmp);
						break;
					}
				}
				if(strlen($numberstr) > 0)
				{
					echo $sql = "call web_savecatch_result('gamebj',{$v},'{$numberstr}')";
					$arrT = $db->Mysqli_Multi_Query($sql);
					$ret .= $v . " ";
				}
			}
			else
			{
				 $kjnum = getbodyc($kjcontent,"<td>{$v}</td>","</td>");
				 $kjnum = trim($kjnum);
				 $arrNum = explode("<td>",$kjnum);
				 if(count($arrNum) > 0)
				 {
					$numberstr = str_replace(",","|",$arrNum[1]);
					if(strlen($numberstr) > 0)
					{
						$sql = "call web_savecatch_result('gamebj',{$v},'{$numberstr}')";
						$arrT = $db->Mysqli_Multi_Query($sql);
						$ret .= $v . " ";
					}
				}
			}
			
		}
	}
	return $ret;
}
function Get360Json($no){
	$url='http://cp.360.cn/i/lotapi.html?datatype=json&do=qkjcode&lotID=265108&issue='.$no.'&t='.rand(100000000,999999999).rand(1111,9999);
	$json=json_decode(vita_get_url_content($url),true);
	if($json[0]['code']==''){
		return false;
	}
	$code=explode('+',$json[0]['code'] );
	$num=str_replace(array(' ','+' ),'|',$code[0] );
	return $num;
}
function GetGameResult()
{
	//$kjNum= Get360();
	//if( !is_array($kjNum))
	$kjNum = GetBeiJingluck8();
	//return $kjNum;
	//var_export($kjNum);
	if( !is_array($kjNum))
		$kjNum = GetRameResult_168kai();
	if( !is_array($kjNum) && $kjNum == "")
		$kjNum = GetGameResult_bjfcdt();

	 return $kjNum;
}
function GetBaidu(){
	$url='http://www.lecai.com/lottery/draw/view/543';
	$html=vita_get_url_content($url);

	preg_match('#var latest_draw_result = (.*?);#s',$html,$kjnum );
	preg_match('#var latest_draw_phase = \'(\d+)\'#',$html,$no );
	preg_match('#var latest_draw_time = \'(.*)\'#',$html,$time );
	$json=json_decode($kjnum[1],true);
	$result[]=array('c_t'=>$no[1],'c_d'=>$time[1],'c_r'=>implode(',',$json['red'] ));
	return $result;
}
function Get360(){
	$url='http://cp.360.cn/kl8/';
	$html=vita_get_url_content($url);
	preg_match('#<em id=\'open_issue\' class=\'mark-date red\'>(\d+)</em>#',$html,$no );
	preg_match('#<b class=\'mark\'>(\d+)</b>#',$html,$fei );
	preg_match('#id=\'open_code_list\'>(.*)</ul>#',$html,$num );
	$num=preg_replace('#<li.*?>(\d+)</li>#', '${1}',$num[1] );
	$num=preg_replace('# #', ',',$num );
	if(strpos($num,'li' )>0)return false;
	$result[]=array('c_t'=>$no[1],'c_d'=>'','c_r'=>$num.$fei[1]);
	return $result;
}
function GetBeiJingluck8(){
	$url="http://www.bwlc.net/bulletin/keno.html";
	$html=vita_get_url_content($url);
	preg_match('#<table class="tb"(.*?)</table>#s',$html,$html);
	preg_match_all('#<tr class=".*">\s+<td>(\d+)</td>\s+<td>(.*)</td>\s+<td>(\d+)</td>\s+<td>(.*)</td>\s+</tr>#',$html[1],$data );
	$result=array();
	foreach ($data[1] as $k=>$v){
		$n=explode(',',$data[2][$k] );
		sort($n);
		$n=implode(',',$n );
		$result[]=array('c_t'=>$v,'c_d'=>$data[4][$k],'c_r'=>$n.','.$data[3][$k]);
	}
	return $result;

}
function vita_get_url_content($url) {
	//if(function_exists('file_get_contents')) {
	//	$file_contents = file_get_contents($url);
	//} else {
	$ch = curl_init();
	$timeout = 5;
	curl_setopt ($ch, CURLOPT_URL, $url);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	curl_setopt($ch, CURLOPT_HEADER, 0); //不返回header部分
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串，而非直接输出
	curl_setopt($ch, CURLOPT_COOKIEJAR,  $cookie_file); //存储cookies
	$file_contents = curl_exec($ch);
	if ($file_contents === FALSE) {

		echo "cURL Error: " . curl_error($ch);
	}
	curl_close($ch);
	//}
	return $file_contents;
}
function GetRameResult_168kai()
{
	$ret = "";
	$url = "http://www.168kai.org/Open/CurrentOpenOne?code=10014&_=" . rand(100000,999999);
	//$url = "http://www.168kai.com/History/HisList?id=10014&date=2015-09-30&_=" . rand(100000,999999);
	//$kjcontent = fsockurl($url);
	$kjcontent = file_get_contents ($url);
	//die($kjcontent);

	$arr = json_decode($kjcontent,true);

	 //var_export($arr);
	$arrList = array($arr);//['list'];

	//var_dump($arrList);
	//die('');	
	return $arrList;
}

function GetGameResult_bjfcdt($theNo)
{
	//$kjcontent = fsockurl( "http://bjfcdt.gov.cn/Happy8/V1/ImageAward.aspx?periodnum=".$theNo ); 
    //$kjcontent = file_get_contents( "http://211.103.171.69/V1/ImageAward.aspx?periodnum=".$theNo );
    $kjcontent = fsockurl( "http://211.103.171.69/Happy8/V1/ImageAward.aspx?periodnum=".$theNo );
    //WriteLog($kjcontent);
    $kjnum = getbodyc( $kjcontent, "awardnum\t= '", "'" );
    $kjnum = explode( "/", $kjnum );
    return $kjnum[0];
}

function GetGameResult_bwlc($theNo)
{
	$ret = "";
	$kjcontent = fsockurl("http://www.bwlc.net/bulletin/prevkeno.html?dates=2015-10-01&page=2");
	$kjnum = getbodyc($kjcontent,"<td>{$theNo}</td>","</td>");
	$kjnum = trim($kjnum);
	$arrNum = explode("<td>",$kjnum);
	if(count($arrNum) > 0)
		$ret = str_replace(",","|",$arrNum[1]);
	return $ret;
}

error_reporting( 0 );
set_time_limit(200);
include_once( "inc/conn.php" );
include_once( "inc/function.php" );
 
if ( $_GET['key'] == "catch_result_beijing" )
{
    $arrRet = array('code'=>'ok', //
    				'no' =>'',
                    'msg'=>'', //错误信息 -1:不在开奖时间内，0：开奖成功，1：该期已开过奖，2：取中奖赔率错误，99：系统错误
                    'log'=>'',
                    'nextid'=>'', //下一盘id
                    'nexttime'=>'' //下一篇开奖时间
        );
    game_go($arrRet);
    if ($arrRet['nextid'] == 'catch_ok')
    {
    	$RandSecond = rand(30,40);
        $sql = "SELECT id,DATE_ADD(kgtime,interval {$RandSecond} second) kgtime FROM game28 WHERE kj = 0 AND kgtime > NOW() limit 1";
        $query = $db->query($sql);
        if($rs = $db->fetch_array( $query ))
        {
             $arrRet['nextid'] = $rs['id'];
             $arrRet['nexttime'] = $rs['kgtime'];
        }
        else
        {
        	$arrRet['nextid'] ='0';
            $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime("+{$RandSecond} second"));
        }
    }
    else
    {
		$RandSecond = rand(20,30);
		$sql = "select date_add(NOW(),INTERVAL {$RandSecond} SECOND) nowtime,id from game28 where kgtime > now() and kj = 0 order by id limit 1";
		$query = $db->query($sql);
		if($rs = $db->fetch_array( $query ))
		{
			$arrRet['nextid'] = $rs['id'];
			$arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime($rs["nowtime"]));
		}
		else
		{
			$arrRet['nextid'] ='0';
            $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime("+{$RandSecond} second"));
		}
    }
    //返回
    echo  json_encode($arrRet);
}

$db->close( );
